import { Inject, Injectable, NotFoundException } from '@nestjs/common';
import { CreateCoralClassDto } from './dto/create-coral-class.dto';
import { UpdateCoralClassDto } from './dto/update-coral-class.dto';
import { PrismaService } from 'src/prisma.service';
import { ConfigService } from '@nestjs/config';
import { ReturnCoralClass } from './dto/return-coral-class.dto';

@Injectable()
export class CoralClassService {
  @Inject()
  prismaService: PrismaService;
  @Inject()
  configService: ConfigService;

  async create(
    createCoralClassDto: CreateCoralClassDto,
  ): Promise<ReturnCoralClass> {
    const res = await this.prismaService.coralClass.create({
      data: createCoralClassDto,
      include: { video: true },
    });
    return res;
  }

  async findAll(): Promise<ReturnCoralClass[]> {
    // 查询所有课程
    const coralClasses = await this.prismaService.coralClass.findMany({
      include: { video: true },
    });
    // 构建返回结果
    return coralClasses;
  }

  async update(
    id: number,
    updateCoralClassDto: UpdateCoralClassDto,
  ): Promise<ReturnCoralClass> {
    // 先检查记录是否存在
    const exists = await this.prismaService.coralClass.findUnique({
      where: { id },
    });

    if (!exists) {
      throw new NotFoundException(`Coral class with ID ${id} not found`);
    }

    // 更新记录
    const updated = await this.prismaService.coralClass.update({
      where: { id },
      data: updateCoralClassDto,
      include: { video: true },
    });

    return updated;
  }

  async remove(id: number): Promise<ReturnCoralClass> {
    // 先检查记录是否存在
    const exists = await this.prismaService.coralClass.findUnique({
      where: { id },
    });

    if (!exists) {
      throw new NotFoundException(`Coral class with ID ${id} not found`);
    }

    // 删除记录
    const deleted = await this.prismaService.coralClass.delete({
      where: { id },
      include: { video: true },
    });

    return deleted;
  }
}
